<template>
    <div>
        <div class="search">
            <a-input
                v-model:value="searchData.search"
                placeholder="搜索名字或者描述"
                style="width: 200px; color: gray; margin-left: 50px;"
                size="large"
                load
            />
            <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">创建日期：</div>
            <a-range-picker v-model:value="dateRange" show-time style="margin-left: 10px;" />
            <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">标签：</div>
            <a-select
                v-model:value="searchData.labelIds"
                mode="multiple"
                placeholder="选择标签"
                :options="labelsAll"
                style="width: 300px; margin-left: 10px;"
            >
            </a-select>
            <a-button size="large" style="margin-left: 50px;" @click="search(1)">搜索</a-button>
        </div>
        <a-list item-layout="vertical" size="large" :pagination="pagination" :data-source="listData" style="margin-top: 20px;">
            <template #renderItem="{ item }">
                <a-list-item key="item.title">
                <template #actions>
                    <span v-for="{ icon, text } in item.actions" :key="icon">
                        <div @click="handleActionClick(text, item.id, item.title)">
                            <component :is="icon" style="margin-right: 8px" />
                            {{ text }}
                        </div>
                    </span>
                </template>
                <template #extra>
                    <img
                    width="200px"
                    height="150px"
                    :src="item.cover"
                    />
                </template>
                <a-list-item-meta :description="item.description">
                    <template #title>
                        <a>{{ item.title }}</a>
                    </template>
                </a-list-item-meta>
                <a-tag
                    v-for="tag in item.labels"
                    :key="tag"
                    :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
                >
                    {{ tag }}
                </a-tag>
                </a-list-item>
            </template>
        </a-list>
    </div>
  </template>

<script lang="ts">
export default {
    name: 'RoomList'
}
</script>

<script lang="ts" setup>
import { DeleteOutlined, EnterOutlined, EditOutlined, ArrowRightOutlined, UserAddOutlined } from '@ant-design/icons-vue';
import { ref, onMounted, reactive } from 'vue';
import type { Dayjs } from 'dayjs';
import { searchRooms, quitRoom, applyJoinRoom } from '@/api/room_api';
import { getLabelList } from '@/api/label_api';
import { message } from 'ant-design-vue';
import router from '@/router';
import { getItem } from '@/api/file_cache';

const listData =  ref<Record<string, any>[]>([]);
interface SearchData {
  search: string,
  labelIds: number[],
  created: boolean,
  joined: boolean,
  managed: boolean,
  beginTime: any,
  EndTime: any
}
const searchData = reactive<SearchData>({
  search: '',
  labelIds: [],
  created: false,
  joined: false,
  managed: false,
  beginTime: null,
  EndTime: null
})
type RangeValue = [Dayjs, Dayjs];
const dateRange = ref<RangeValue>();
const labelsAll = ref<{label: string, value: number, disabled: boolean}[]>([])
const pagination = {
    onChange: (page: number) => {
        search(page)
    },
    pageSize: 5,
    total: 0,
};
const props = defineProps(['id'])
const emits = defineEmits(['roomEdit'])

onMounted(async () => {
    // 请求label下拉框数据
    await getLabelList(1)
    .then(response => {
        for (let index = 0; index < response.data.length; index++) {
        labelsAll.value.push(response.data[index])
        }
        console.log(response.data)
    })
    .catch(error => {})
    await search(1)
})

const search = async (page:number) => {
    if (dateRange.value != undefined && dateRange.value.length == 2) {
        searchData.beginTime = dateRange.value?.[0].format('YYYY-MM-DD HH:mm:ss')
        searchData.EndTime = dateRange.value?.[1].format('YYYY-MM-DD HH:mm:ss')
    }
    if (props.id === 'joined') {
        searchData.joined = true
    } else if (props.id === 'managed') {
        searchData.managed = true
    } else if (props.id === 'created') {
        searchData.created = true
    }
    await searchRooms(searchData, page, 5)
    .then(async resp => {
        pagination.total = resp.data.total
        listData.value = []
        for (let i = 0; i < resp.data.list.length; i++) {
            // let coverUrl = String(resp.data.list[i].coverUrl);
            // let coverData: Blob | undefined = undefined;
            // await getItem(coverUrl)
            //     .then(resp => {
            //     coverData = resp;
            //     })
            //     .catch(err => {
            //     console.error(err);
            //     })
            let data = {
                title: resp.data.list[i].name,
                description: resp.data.list[i].description,
                labels: resp.data.list[i].labelNames,
                cover: resp.data.list[i].coverUrl,
                id: resp.data.list[i].id,
                actions: [{}],
            }
            if (resp.data.list[i].isCreator === true) {
                data.actions.push({ icon: EnterOutlined, text: '进入' }, { icon: EditOutlined, text: '管理' },{ icon: DeleteOutlined, text: '删除' })
            } else if (resp.data.list[i].isAdmin === true) {
                data.actions.push({ icon: EnterOutlined, text: '进入' }, { icon: EditOutlined, text: '管理' })
            } else if (resp.data.list[i].isMember === true) {
                data.actions.push({ icon: EnterOutlined, text: '进入' }, {icon: ArrowRightOutlined, text: '退出'})
            } else {
                data.actions.push({ icon: UserAddOutlined, text: '申请加入'})
            }
            listData.value.push(data)
        }
        searchData.search = ""
        searchData.labelIds = []
        searchData.beginTime = null
        searchData.EndTime = null
        dateRange.value = undefined;
    })
    .catch(error => {})
};

const handleActionClick = (text:string, id:number, name:string) => {
    switch (text) {
        case "进入":
            handleRoomEnter(id)
            break
        case "管理":
            handleRoomUpdate(id)
            break
        case "删除":
            handleRoomDelete(id)
            break
        case "退出":
            handleQuitRoom(id, name)
            break
        case "申请加入":
            handleApplyJoin(id, name)
            break
    }
}

const handleRoomEnter = (id:any) => {
    router.push({name: 'roomDetail', params:{id: id}})
};

const handleRoomUpdate = (id:any) => {
    emits('roomEdit', id)
};

const handleRoomDelete = (id:any) => {
    console.log(id)
}

const handleQuitRoom = async (id:number, name:string) => {
    await quitRoom({
        name: name,
        id: id
    })
    .then(resp => {
        message.info("退出房间成功")
    })
    .catch(err => {})
}

const handleApplyJoin = async (id:number, name:string) => {
    await applyJoinRoom({
        id: id,
        name: name
    })
    .then(resp => {
        message.info("已申请进入房间")
    })
    .catch(err => {})
}
</script>

<style scoped>
.search {
  display: flex;
  margin-top: 20px;
}
</style>